import { BTNode } from "../BTNode";
import { BTState } from "../BTState";
import { BTDecorator } from "./BTDecorator";

/**
 * [行为树]重复节点
 * 重复执行n次子节点
 * 即使子任务返回失败 它也可以选择继续执行子任务
 */
export class BTRepeater<T = any> extends BTDecorator<T> {

    /** 已执行次数 */
    count: number;

    constructor(
        /** 重复次数 0:永远重复 */
        public repeat: number = 0,
        /** 当子节点返回失败时是否立即返回 */
        public endOnFail: boolean = false,
        /** 子节点 */
        child: BTNode
    ) {
        super(child)
    }

    protected onStart(ctx: T): void {
        super.onStart(ctx);
        this.count = 0;
    }

    process(ctx: T): BTState {
        const state = this.child.tick(ctx);
        ++this.count;

        if (this.endOnFail && state == BTState.fail)
            return BTState.succ;

        if (this.repeat > 0 && this.count === this.repeat) {
            return BTState.succ;
        }

        return BTState.run;
    }

}